﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lucky_bgy
{
    public static class FileHelper
    {

        public static DataTable ImportTxt()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            openFileDialog.Title = "信息导入--" + ConfigHelper.get("main_title");
            //openFileDialog.FileName = string.Format("BFD{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string fileName = openFileDialog.FileName; //得到：文件路径+文件名+文件后缀名

                string strName = fileName.Substring(fileName.LastIndexOf('\\') + 1); //得到：文件名+文件后缀名
                strName = strName.Remove(strName.LastIndexOf(".")); //得到：文件名

                if (fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower() != "txt")
                {
                    MessageBox.Show("导入文件类型不正确，请导入TXT文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                //读取文本信息
                FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.Default);
                //streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                //string strLine = streamReader.ReadLine();

                DataTable dt = new DataTable();
                dt.Columns.Add("tel", typeof(string));
                dt.Columns.Add("user_name", typeof(string));

                while (!streamReader.EndOfStream)
                {
                    string[] items = streamReader.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    dr["tel"] = items[0];
                    dr["user_name"] = items[1];

                    dt.Rows.Add(dr);
                }

                if (dt.Rows.Count > 0)
                {
                    return dt;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

            

        }
    }
}